﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using Bridge.Base.Converter;
using Pathfinder.Base.Constructs;
using Pathfinder.Utilities;

namespace Pathfinder.Converters.D20PFSRD
{
    public class PFSRDPossibleUriFinder : PossibleUriFinder<PathfinderCharacter>
    {
        #region IPossibleUriFinder Members

        public override Dictionary<string, Uri> GetAllPossibleUris()
        {
            Uri uri = new UriBuilder("http://www.d20pfsrd.com/bestiary").Uri;
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.Timeout = 10000;
            WebResponse webResponse = webRequest.GetResponse();

            string webPage = null;
            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
            {
                if (streamReader.ReadUntilString("<a name=\"TOC-A-\">"))
                {
                    webPage = streamReader.StripHTML("((?<=</a>)|(?<=^)).+?((?=<a href=\"http://www.d20pfsrd.com/bestiary/monster-listings/)|(?=$))");
                }
            }
            if (webPage != null)
            {
                Dictionary<string, Uri> uris = new Dictionary<string, Uri>();
                foreach (Match match in Regex.Matches(webPage, "<a href=\"http://www.d20pfsrd.com/bestiary/monster-listings/.+?/.+?\">.+?</a>", RegexOptions.Singleline | RegexOptions.IgnoreCase))
                {
                    Uri foundUri = new UriBuilder(Regex.Match(match.Value, "(?<=\\\").+?(?=\\\")\")").Value).Uri;
                    string name = Regex.Match(match.Value, "(?<=>).+?(?=<)").Value;
                    uris.Add(name, foundUri);
                }
                return uris;
            }
            return null;
        }

        public override IEnumerable<UriConverter<PathfinderCharacter>> GetCompatibleConverters()
        {
            List<UriConverter<PathfinderCharacter>> converters = new List<UriConverter<PathfinderCharacter>>();
            converters.Add(new PFSRDUriConverter());
            return converters;
        }

        #endregion

        public override UriConverter<PathfinderCharacter> DefaultConverter
        {
            get { throw new NotImplementedException(); }
        }
    }
}
